<?php

namespace app\apiadmin\controller\b2bcrm;

use app\common\controller\Backend;
use think\Db;
use think\Validate;

class Clue extends Backend
{

    protected $rule = [
        'contact' => 'require|max:6',
        'mobile' => 'number|max:11',
        'weixin' => 'max:15',
        'telephone' => 'max:20',
        'qq' => 'max:15',
        'email' => 'max:30'
    ];

    protected $message = [
        'contact' => '联系人必填，且最多6个字',
        'mobile' => '手机号为11位数字',
        'weixin' => '微信最多15位',
        'telephone' => '座机最多20位',
        'qq' => 'QQ最多15位',
        'email' => '邮箱最多30位'
    ];

    public function _initialize()
    {
        parent::_initialize(); // TODO: Change the autogenerated stub
    }

    /*
     * 线索列表
     * */
    public function index()
    {
        $list_type = input('get.list_type/d', 0, 'intval');
        $key_type = input('get.key_type/d', 0, 'intval');
        $keyword = input('get.keyword/s', '', 'trim');
        $current_page = input('get.page/d', 1, 'intval');
        $pagesize = input('get.pagesize/d', 10, 'intval');
        $trade = input('get.trade/d', 0, 'intval');
        $district = input('get.district/a', []);
        $creat_id = input('get.creat_id/d', 0, 'intval');
        $admin_id = input('get.admin_id/d', 0, 'intval');
        $sort = input('get.sort/s', 'DESC', 'trim,strtoupper'); // 排序方式 asc dec
        $sort_type = input('get.sort_type/s', '', 'trim');
        $collection = input('get.collection/s', '', 'trim');
        $follow_count = input('get.follow_count/d', 0, 'intval');
        $search_type = input('get.search_type/d', 0, 'intval');

        // 排序规则【ASC|DESC】
        if (!in_array($sort, ['ASC', 'DESC'])) {
            $sort = 'DESC';
        }

        switch ($sort_type) {
            case 'collection_time':
                // 领取时间
                $order = 'a.collection_time ' . $sort . ',a.id DESC';
                break;
            case 'last_visit_time':
                // 最近跟进
                $order = 'a.last_visit_time ' . $sort;
                break;
            default:
                if ($list_type === 2) {
                    $order = 'a.collection_time DESC,a.updatetime DESC,a.id DESC';
                } else {
                    $order = 'a.updatetime DESC,a.id DESC';
                }
                break;
        }

        $where = ['is_customer' => 0];
        if ($key_type > 0 && $keyword != '') {
            switch ($key_type) {
                case 1:// 搜索名称
                    $where['a.name'] = ['like', '%' . $keyword . '%'];
                    break;
                case 2: // 搜索手机号
                    $where['a.mobile'] = ['like', '%' . $keyword . '%'];
                    break;
            }
        }

        // 查询条件 - 跟进状态
        if (!empty($search_type)) {
            switch ($search_type) {
                case 1: // 今日跟进
                    $beginToday = mktime(0, 0, 0, date('m'), date('d'), date('Y'));
                    $where['a.last_visit_time'] = ['gt', $beginToday];
                    break;
                case 2: // 30天内跟进过
                    $time = strtotime(date("Y-m-d", strtotime("-30 day")));
                    $where['a.last_visit_time'] = ['gt', $time];
                    break;
                case 3: // 7天未跟进
                    $time = strtotime(date("Y-m-d", strtotime("-7 day")));
                    $where['a.last_visit_time'] = ['lt', $time];
                    break;
                case 4: // 15天未跟进
                    $time = strtotime(date("Y-m-d", strtotime("-15 day")));
                    $where['a.last_visit_time'] = ['lt', $time];
                    break;
                case 5: // 30天未跟进
                    $time = strtotime(date("Y-m-d", strtotime("-30 day")));
                    $where['a.last_visit_time'] = ['lt', $time];
                    break;
                case 6: // 从未跟进
                    $where['a.last_visit_time'] = 0;
                    break;
                case 7: // 即将转为公客
                    $customer_fall_seas = model('b2bcrm.CrmSysConfig')
                        ->getConfigByKey('customer_fall_seas');
                    if (isset($customer_fall_seas) && !empty($customer_fall_seas)) {
                        $day = $customer_fall_seas - 7;
                        $time = strtotime(date("Y-m-d", strtotime("-$day day")));
                        $where['a.last_visit_time'] = ['lt', $time];
                    } else {
                        $where['a.last_visit_time'] = ['lt', 0];
                    }
                    break;
            }
        }
        if (!empty($collection)) {
            //今日时间时间戳
            $timestampToday = strtotime('today');
            //本周时间时间戳
            $week_start_time = mktime(0, 0, 0, date('m'), date('d') - date('w') + 1, date('y'));
            $week_over_time = mktime(23, 59, 59, date('m'), date('d') - date('w') + 7, date('y'));
            //本月时间时间戳
            $month_start_time = mktime(0, 0, 0, date('m'), 1, date('Y'));
            $month_over_time = mktime(23, 59, 59, date('m'), date('t'), date('Y'));
            switch ($collection) {
                case 1:// 今日新增线索
                    $where['a.collection_time'] = ['>=', $timestampToday];
                    break;
                case 2: // 本周新增线索
                    $where['a.collection_time'] = [['>=', $week_start_time], ['<', $week_over_time], 'and'];
                    break;
                case 3: // 本月新增线索
                    $where['a.collection_time'] = [['>=', $month_start_time], ['<', $month_over_time], 'and'];
                    break;
                default:
                    /**
                     * 【ID1000677】
                     * 【优化】销售看板新增提示语、点击跳转、样式优化
                     * cy 2023-06-28
                     * 指定月份的筛选
                     */
                    $timestamp = strtotime($collection);
                    if (false !== $timestamp && $timestamp > 0) {
                        $monthStart = strtotime(getMonthRange($collection));
                        $monthEnd = strtotime(getMonthRange($collection, false));
                        $where['a.collection_time'] = ['between', [$monthStart, $monthEnd]];
                    }
                    break;
            }
        }
        if ($follow_count > 0) {
            switch ($follow_count) {
                case 1:// 跟进0次线索
                    $where['a.follow_count'] = ['=', 0];
                    break;
                case 2: // 跟进1次线索
                    $where['a.follow_count'] = ['=', 1];
                    break;
                case 3: // 跟进2次线索
                    $where['a.follow_count'] = ['=', 2];
                    break;
                case 4: // 跟进3次及以上线索
                    $where['a.follow_count'] = ['>=', 3];
                    break;
            }
        }
        if ($trade > 0) {
            $where['a.trade'] = $trade;
        }
        if ($admin_id > 0) {
            $where['a.admin_id'] = $admin_id;
        }
        if (!empty($district) && is_array($district)) {
            if (isset($district[0]) && !empty($district[0])) {
                $where['a.district1'] = $district[0];
            }
            if (isset($district[1]) && !empty($district[1])) {
                $where['a.district2'] = $district[1];
            }
            if (isset($district[2]) && !empty($district[2])) {
                $where['a.district3'] = $district[2];
            }
        }

        if ($creat_id > 0) {
            $where['a.creat_id'] = $creat_id;
        }
        switch ($list_type) {
            case 1: // 线索公海
                $where['a.admin_id'] = 0;
                break;
            case 2: // 我的线索
                $where['a.admin_id'] = $this->admininfo->id;
                break;
            default: // 全部线索
                break;
        }

        $field = 'a.id,a.`name`,a.admin_id,a.mobile,a.contacts,a.weixin,a.district1,a.district2,a.district3,a.district,a.address,a.updatetime,a.createtime,a.creat_id,a.last_visit_time,a.remark,a.trade,count(b.id) as follow_count,a.collection_time,count(b.id) as follow_count,a.tripartite_id,a.telephone';
        $list = model('b2bcrm.CrmClue')->getList($where, $order, $current_page, $pagesize, $field);

        $category_data = model('Category')->getCache('QS_trade');
        $category_district_data = model('CategoryDistrict')->getCache();
        if (empty($list)) {
            $this->ajaxReturn(200, '获取数据成功', []);
        }

        $adminlist = $this->adminlist();
        $cluelist = [];
        foreach ($list['rows'] as $v) {
            $v['admin_username'] = isset($adminlist[$v['admin_id']]) ? $adminlist[$v['admin_id']] : '';
            $v['creat_username'] = isset($adminlist[$v['creat_id']]) ? $adminlist[$v['creat_id']] : '';
            $v['trade'] = isset($category_data[$v['trade']]) ? $category_data[$v['trade']] : '';
            $v['district1'] = isset($category_district_data[$v['district1']]) ? $category_district_data[$v['district1']] : '';
            $v['district2'] = isset($category_district_data[$v['district2']]) ? $category_district_data[$v['district2']] : '';
            $v['district3'] = isset($category_district_data[$v['district3']]) ? $category_district_data[$v['district3']] : '';
            $v['district'] = $v['district1'] . $v['district2'] . $v['district3'];
            $v['last_visit_time'] = intval($v['last_visit_time']);
            if ($v['last_visit_time'] > 0) {
                // 最后跟进
                $v['not_following_day'] = intval((time() - $v['last_visit_time']) / 86400); // 未跟进时长
                $v['last_visit_time'] = date('Y-m-d H:i:s', $v['last_visit_time']); // 最后跟进时间
                // 未跟进时长（天）
            } else {
                // 最后跟进
                $v['last_visit_time'] = '';
                // 未跟进时长（天）
                $v['not_following_day'] = -1;
            }

            // 领取时间
            $v['collection_time'] = !empty($v['collection_time']) ? date('Y-m-d H:i:s', $v['collection_time']) : '';

            unset($v['creat_id']);
            $cluelist[] = $v;
        }
        $return['items'] = $cluelist;
        $return['total'] = $list['pages']['record_num'];
        $return['current_page'] = $current_page;
        $return['pagesize'] = $pagesize;
        $return['total_page'] = $list['pages']['total_page'];
        $this->ajaxReturn(200, '获取数据成功', $return);
    }

    /*
     * 线索详情
     * */
    public function details()
    {
        $clue_id = input('get.clue_id/d', 0, 'intval');
        if ($clue_id <= 0) {
            $this->ajaxReturn(500, '线索id错误', []);
        }
        $crm_clue = model('b2bcrm.CrmClue')->where('id', $clue_id)->find();
        if (!isset($crm_clue) || empty($crm_clue)) {
            $this->ajaxReturn(500, '线索不存在', []);
        }

        $category_district_data = model('CategoryDistrict')->getCache();
        $adminlist = $this->adminlist();
        $crm_clue['admin_username'] = !empty($adminlist[$crm_clue['admin_id']]) ? $adminlist[$crm_clue['admin_id']] : '';
        $crm_clue['creat_username'] = !empty($adminlist[$crm_clue['creat_id']]) ? $adminlist[$crm_clue['creat_id']] : '';
        $district1 = !empty($category_district_data[$crm_clue['district1']]) ? $category_district_data[$crm_clue['district1']] : '';
        $district2 = !empty($category_district_data[$crm_clue['district2']]) ? $category_district_data[$crm_clue['district2']] : '';
        $district3 = !empty($category_district_data[$crm_clue['district3']]) ? $category_district_data[$crm_clue['district3']] : '';
        $crm_clue['district'] = [$crm_clue['district1'], $crm_clue['district2'], $crm_clue['district3']];
        $crm_clue['district_text'] = $district1 . $district2 . $district3;
        $crm_clue['last_visit_time'] = !empty($crm_clue['last_visit_time']) ? date('Y-m-d H:i:s', $crm_clue['last_visit_time']) : '从未跟进';
        $crm_clue['visit_count'] = model('b2bcrm.CrmFollowUp')->where(['clue_id' => $clue_id])->count();
        $crm_clue['scale'] = empty($crm_clue['scale']) ? null : $crm_clue['scale'];
        $crm_clue['trade'] = empty($crm_clue['trade']) ? null : $crm_clue['trade'];

        unset($crm_clue['uid'], $crm_clue['utype'], $crm_clue['admin_id'], $crm_clue['creat_id']);
        $this->ajaxReturn(200, '获取数据成功', $crm_clue);
    }

    /*
     * 释放(批量释放)
     * */
    public function release()
    {
        $clue_id = input('post.clue_id/a', []);
        if (empty($clue_id)) {
            $this->ajaxReturn(500, '请选择线索');
        }
        $clue_count = model('b2bcrm.CrmClue')->getDataNum(['a.id' => ['in', $clue_id]]);
        if ($clue_count == 0) {
            $this->ajaxReturn(500, '请选择正确的数据');
        }
        Db::startTrans();
        try {
            $update = model('b2bcrm.CrmClue')
                ->allowField(true)
                ->isUpdate(true)
                ->save(['admin_id' => 0], ['id' => ['in', $clue_id]]
                );
            if (false === $update) {
                throw new \Exception(model('b2bcrm.CrmClue')->getError());
            }
            $release = [];

            foreach ($clue_id as $v) {
                $release[] = [
                    'clue_id' => $v,
                    'create_time' => time(),
                    'operation_type' => 2,
                    'operator' => 2,
                    'utype' => 0,
                    'admin_id' => $this->admininfo->id,
                ];
            }
            $release_result = model('b2bcrm.CrmClueRelease')
                ->isUpdate(false)
                ->saveAll($release);
            if ($release_result === false) {
                throw new \Exception(model('b2bcrm.CrmClueRelease')->getError());
            }

            $clue_list = model('b2bcrm.CrmClue')->where('id', 'in', $clue_id)->column('id,name');

            // 日志
            $log_field = '释放线索';
            foreach ($clue_list as $c_id => $c_name) {
                $log_field .= '{' . $c_name . '}(线索ID:' . $c_id . ')；';
            }
            $log_result = model('AdminLog')->writeLog(
                $log_field,
                $this->admininfo,
                0,
                1
            );
            if (false === $log_result) {
                throw new \Exception(model('AdminLog')->getError());
            }

            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollBack();
            $this->ajaxReturn(500, $e->getMessage());
        }

        $this->ajaxReturn(200, '释放成功');
    }


    /*
     * 领取(批量领取)
     * */
    public function receive()
    {
        $clue_id = input('post.clue_id/a', []);
        if (empty($clue_id)) {
            $this->ajaxReturn(500, '请选择线索');
        }
        $clue_count = model('b2bcrm.CrmClue')->getDataNum(['a.id' => ['in', $clue_id]]);
        if ($clue_count == 0) {
            $this->ajaxReturn(500, '请选择线索');
        }
        try {

            $sys_configs = model('b2bcrm.CrmSysConfig')->getDateByCategory('thread');
            $sys_config = [];
            foreach ($sys_configs as $v) {
                if ($v['is_open'] == 1) {
                    $sys_config[$v['key']] = $v['value'];
                }
            }
            // 领取天数限制
            if (isset($sys_config['thread_receive_limit'])) {
                if ($sys_config['thread_receive_limit'] == 0) {
                    $this->ajaxReturn(500, '当前不允许主动领取线索', []);
                }
                $where = [
                    'admin_id' => $this->admininfo->id,
                    'operation_type' => 1,
                    'operator' => 1,
                    'utype' => 0
                ];
                $count = model('b2bcrm.CrmClueRelease')
                    ->where($where)
                    ->whereTime('create_time', 'today')
                    ->count();

                if (($count + $clue_count) > $sys_config['thread_receive_limit']) {
                    $can_num = $sys_config['thread_receive_limit'] - $count;
                    if ($can_num < 0) {
                        $can_num = 0;
                    }
                    $this->ajaxReturn(500, '当天领取限制【' . $sys_config['thread_receive_limit'] . '】个，你已领取【' . $count . '】个，还可领取【' . $can_num . '】个！', []);
                }
            }

            /**
             * 【ID1000518】、
             * 【新增】CRM设置客户总数、线索总数限定
             * yx - 2023.03.21
             * [新增]:
             */
            if (isset($sys_config['thread_total_limit'])) {
                if ($sys_config['thread_total_limit'] == 0) {
                    $this->ajaxReturn(500, '当前销售线索总数上限不允许领取', []);
                }
                $thread_total_count = model('b2bcrm.CrmClue')
                    ->where([
                        'admin_id' => $this->admininfo->id,
                        'is_customer' => 0
                    ])
                    ->count();

                if (($thread_total_count + $clue_count) > $sys_config['thread_total_limit']) {
                    $total_can_num = $sys_config['thread_total_limit'] - $thread_total_count;
                    if ($total_can_num < 0) {
                        $total_can_num = 0;
                    }
                    $this->ajaxReturn(500, '线索最大领取上限【' . $sys_config['thread_total_limit'] . '】个，你已领取【' . $thread_total_count . '】个，还可领取【' . $total_can_num . '】个！', []);
                }
            }

            foreach ($clue_id as $v) {
                /**
                 * CRM线索领取
                 * yx - 2022.11.10
                 */

                // 1.查询最后一次释放记录
                $lastRelease = model('b2bcrm.CrmClueRelease')
                    ->alias('a')
                    ->join('crm_clue b', 'a.clue_id=b.id', 'left')
                    ->where([
                        'a.clue_id' => $v,
                        'a.admin_id' => $this->admininfo->id,
                        'a.operation_type' => 2,
                        'a.utype' => 0
                    ])
                    ->order('a.create_time', 'DESC')
                    ->field('a.create_time, a.operator, b.name')
                    ->find();

                if (isset($lastRelease) && !empty($lastRelease)) {
                    $crmClueRelease = $lastRelease->toArray();

                    // 操作人员 1-系统 2-销售
                    switch ($lastRelease['operator']) {
                        case 1:
                            if ($sys_config['thread_forbidden_sys'] == 0) {
                                $this->ajaxReturn(500, '系统配置系统自动释放线索不允许领取', []);
                            }
                            $thread_forbidden_sys = $sys_config['thread_forbidden_sys'] * 86400;

                            $time_diff = strtotime($crmClueRelease['create_time']) + $thread_forbidden_sys;

                            if (time() <= $time_diff) {
                                $this->ajaxReturn(500, '【' . $crmClueRelease['name'] . '】线索，系统自动释放后' . $sys_config['thread_forbidden_sys'] . '天内不能再领取该线索', []);
                            }
                            break;

                        case 2:
                            if ($sys_config['thread_forbidden_sale'] == 0) {
                                $this->ajaxReturn(500, '系统配置主动释放线索不允许领取', []);
                            }
                            $thread_forbidden_sale = $sys_config['thread_forbidden_sale'] * 86400;

                            $timediff = strtotime($crmClueRelease['create_time']) + $thread_forbidden_sale;

                            if (time() <= $timediff) {
                                $this->ajaxReturn(500, '【' . $crmClueRelease['name'] . '】线索，主动释放后' . $sys_config['thread_forbidden_sale'] . '天内不能再领取该线索', []);
                            }
                            break;

                        default:
                            return $this->ajaxReturn(200, '客户异常释放，领取失败', []);

                    }
                }
            }

            Db::startTrans();

            $receive = model('b2bcrm.CrmClueRelease')->releaseAdd($clue_id, $this->admininfo->id, 1, 1, 0);
            if ($receive === false) {
                $this->ajaxReturn(500, '领取失败', []);
            }

            $receive_result = model('b2bcrm.CrmClue')
                ->isUpdate('true')
                ->save(['admin_id' => $this->admininfo->id, 'collection_time' => time()], ['id' => ['in', $clue_id]]);
            if ($receive_result === false) {
                throw new \Exception(model('b2bcrm.CrmClueRelease')->getError());
            }

            $clue_list = model('b2bcrm.CrmClue')->where('id', 'in', $clue_id)->column('id,name');

            // 日志
            $log_field = '领取线索';
            foreach ($clue_list as $c_id => $c_name) {
                $log_field .= '{' . $c_name . '}(线索ID:' . $c_id . ')；';
            }
            $log_result = model('AdminLog')->writeLog(
                $log_field,
                $this->admininfo,
                0,
                1
            );
            if (false === $log_result) {
                throw new \Exception(model('AdminLog')->getError());
            }

            Db::commit();
            $this->ajaxReturn(200, '领取成功', []);
        } catch (\Exception $e) {
            Db::rollback();
            $this->ajaxReturn(500, '领取成功', ['err_msg' => $e->getMessage()]);
        }
    }


    /*
     * 线索添加
     * */
    public function clueAdd()
    {
        $district = input('post.district/a', []);
        $district_count = count($district);
        $input_data = [
            'name' => input('post.name/', '', 'trim'),  // 线索名称
            // 'mobile' => input('post.mobile/d', '', 'trim'),  // 联系电话
            // 'contacts' => input('post.contacts/s', '', 'trim'),  // 联系人
            'weixin' => input('post.weixin/s', '', 'trim'),  // 微信
            'district1' => !empty($district[0]) ? intval($district[0]) : 0, // 省
            'district2' => !empty($district[1]) ? intval($district[1]) : 0, // 市
            'district3' => !empty($district[2]) ? intval($district[2]) : 0, // 区
            'district' => $district_count - 1,
            'address' => input('post.address/s', '', 'trim'), // 详细地址
            'creat_id' => $this->admininfo->id,
            'remark' => input('post.remark/s', '', 'trim'),
            'trade' => input('post.trade/d', 0, 'intval'),
            'scale' => input('post.scale/d', 0, 'intval')
        ];

        // 联系方式
        $contactList = input('post.contact_list/a', []);
        if (empty($contactList)) {
            $this->ajaxReturn(500, '缺少联系方式');
        }
        $mainContact = [];
        foreach ($contactList as $contactInfo) {
            if (empty($contactInfo['contact'])) {
                $this->ajaxReturn(500, '请填写联系人');
            }
            if (empty($contactInfo['mobile']) && empty($contactInfo['telephone'])) {
                $this->ajaxReturn(500, '请填写联系电话或固话二选一');
            }
            if (!empty($contactInfo['mobile']) && !fieldRegex($contactInfo['mobile'], 'mobile')) {
                $this->ajaxReturn(500, '联系电话格式错误');
            }
            if ($contactInfo['is_main'] == 1) {
                $mainContact = [
                    'contact' => $contactInfo['contact'],
                    'mobile' => $contactInfo['mobile'],
                    'telephone' => isset($contactInfo['telephone']) ? $contactInfo['telephone'] : ''
                ];
            }
        }
        // 如果没有设置主要联系人，那默认取第一条
        if (empty($mainContact)) {
            $mainContact = [
                'contact' => $contactList[0]['contact'],
                'mobile' => $contactList[0]['mobile'],
                'telephone' => isset($contactInfo[0]['telephone']) ? $contactInfo[0]['telephone'] : ''
            ];
            $contactList[0]['is_main'] = 1;
        }
        $input_data['contacts'] = $mainContact['contact'];
        $input_data['mobile'] = $mainContact['mobile'];
        $input_data['telephone'] = $mainContact['telephone'];
        $preg_wechat = '/^[_a-zA-Z0-9]{5,19}+$/isu';
        if (!empty($input_data['weixin']) && !preg_match($preg_wechat, $input_data['weixin'])) {
            $this->ajaxReturn(500, '微信号格式错误');
        }
        $sale = input('post.sale/d', 0, '');
        if ($sale > 0) {
            /**
             * 【ID1000518】、
             * 【新增】CRM设置客户总数、线索总数限定
             * yx - 2023.03.21
             * [新增]:
             */
            $thread_total_limit = model('b2bcrm.CrmSysConfig')->getConfigByKey('thread_total_limit');
            if (isset($thread_total_limit)) {
                if ($thread_total_limit == 0) {
                    $this->ajaxReturn(500, '当前销售线索总数上限不允许领取', []);
                }
                $thread_total_count = model('b2bcrm.CrmClue')
                    ->where([
                        'admin_id' => $this->admininfo->id,
                        'is_customer' => 0
                    ])
                    ->count();

                if (($thread_total_count + 1) > $thread_total_limit) {
                    $this->ajaxReturn(500, '已达线索总数上限', []);
                }
            }

            $input_data['admin_id'] = $this->admininfo->id;
            $input_data['collection_time'] = time(); // 添加领取时间
        }

        $sys_configs = model('b2bcrm.CrmSysConfig')->getDateByCategory('thread');
        $sys_config = [];
        foreach ($sys_configs as $v) {
            if ($v['is_open'] == 1) {
                $sys_config[$v['key']] = $v['value'];
            }
        }
        /**
         * 【bug】
         * 线索名称重复验证修改
         * zch 2022.9.19
         */
        if (isset($sys_config['thread_duplicate_name']) && $sys_config['thread_duplicate_name'] == 0) {
            $count = model('b2bcrm.CrmClue')->getDataNum(['a.name' => $input_data['name']]);
            if ($count > 0) {
                $this->ajaxReturn(500, '线索名称已存在');
            }
        }

        Db::startTrans();
        try {
            $add_crmclue = model('b2bcrm.CrmClue')
                ->allowField(true)
                ->validate('CrmClue.add')
                ->isUpdate(false)->save($input_data);
            if (false === $add_crmclue) {
                throw new \Exception(model('b2bcrm.CrmClue')->getError());
            }

            // 新增联系人
            $insertContactData = [];
            foreach ($contactList as $contactInfo) {
                $insertContactData[] = [
                    'clue_id' => model('b2bcrm.CrmClue')->id,
                    'contact' => $contactInfo['contact'],
                    'mobile' => $contactInfo['mobile'],
                    'is_main' => $contactInfo['is_main'],
                    'addtime' => time()
                ];
            }
            $result = db('crm_clue_contact')->insertAll($insertContactData);
            if (empty($result)) {
                throw new \Exception('新增联系人失败');
            }

            // 日志
            $log_result = model('AdminLog')->writeLog(
                '新增线索{' . $input_data['name'] . '}(线索ID:' . model('b2bcrm.CrmClue')->id . ')',
                $this->admininfo,
                0,
                2
            );
            if (false === $log_result) {
                throw new \Exception(model('AdminLog')->getError());
            }
            Db::commit();
            $this->ajaxReturn(200, '添加成功');
        } catch (\Exception $e) {
            Db::rollback();
            $this->ajaxReturn(500, $e->getMessage());
        }

    }

    /*
     * 线索编辑
     * */
    public function clueEdit()
    {
        $clue_id = input('post.clue_id/d', 0, 'intval');
        if ($clue_id <= 0) {
            $this->ajaxReturn(500, '线索id错误', []);
        }

        $clueField = [
            'id',
            'contacts',
            'mobile',
        ];
        $clueInfo = model('b2bcrm.CrmClue')->field($clueField)->where('id', $clue_id)->find();
        if (is_null($clueInfo) || empty($clueInfo)) {
            $this->ajaxReturn(500, '未找到线索信息', []);
        }
        $clueInfo = $clueInfo->toArray();
        $input = input('post.', []);
        unset($input['createtime'], $input['updatetime'], $input['last_visit_time']);
        /**
         * 【bug】
         * 线索名称重复验证修改
         * zch 2022.9.19
         */
        $sys_configs = model('b2bcrm.CrmSysConfig')->where(['key' => 'thread_duplicate_name', 'category' => 'thread'])->value('value');
        if ($sys_configs == 0) {
            $clue_find = model('b2bcrm.CrmClue')->where(['name' => $input['name']])->find();
            if (!empty($clue_find) && $clue_find['id'] != $clue_id) {
                $this->ajaxReturn(500, '线索名称已存在');
            }
        }
        if (empty($input['mobile']) && empty($input['telephone'])) {
            $this->ajaxReturn(500, '请填写联系手机或座机二选一');
        }
        if (!empty($input['mobile']) && !fieldRegex($input['mobile'], 'mobile')) {
            $this->ajaxReturn(500, '联系电话格式错误');
        }
        $preg_wechat = '/^[_a-zA-Z0-9]{5,19}+$/isu';
        if (!empty($input['weixin']) && !preg_match($preg_wechat, $input['weixin'])) {
            $this->ajaxReturn(500, '微信号格式错误');
        }

        Db::startTrans();
        try {
            $edit = model('b2bcrm.CrmClue')->allowField(true)
                ->validate('CrmClue.edit')
                ->isUpdate(true)->save($input, ['id' => $clue_id]);
            if (false === $edit) {
                throw new \Exception(model('b2bcrm.CrmClue')->getError());
            }

            // 处理线索联系人 edc 2022-11-22
            $this->_handleClueContact($input, $clueInfo);

            // 日志
            $log_result = model('AdminLog')->writeLog(
                '编辑线索{' . $input['name'] . '}(线索ID:' . $clue_id . ')资料',
                $this->admininfo,
                0,
                3
            );
            if (false === $log_result) {
                throw new \Exception(model('AdminLog')->getError());
            }
            Db::commit();
            $this->ajaxReturn(200, '修改成功', []);
        } catch (\Exception $e) {
            Db::rollback();
            $this->ajaxReturn(500, $e->getMessage());
        }
    }

    /*
     * 列表导出
     * */
    public function export()
    {
        $list_type = input('post.list_type/d', 0, 'intval');
        $clue_id = input('post.clue_id/a', []);
        $this->checkExportAccess();
        if (!is_array($clue_id) || empty($clue_id)) {
            $this->ajaxReturn(500, '请选择要导出的线索', []);
        }
        $where['a.id'] = ['in', $clue_id];
        switch ($list_type) {
            case 1: // 线索公海
                $where['a.admin_id'] = 0;
                break;
            case 2: // 我的线索
                $where['a.admin_id'] = $this->admininfo->id;
                break;
            default: // 全部线索
                break;
        }

        $field = 'a.id,a.name,a.admin_id,a.mobile,a.contacts,a.weixin,a.district1,a.district2,a.district3,a.address,a.updatetime,a.createtime,a.creat_id,a.last_visit_time,a.remark,a.trade';
        $list = model('b2bcrm.CrmClue')->getList($where, ['updatetime DESC'], 1, 'all', $field);
        $category_data = model('Category')->getCache('QS_trade');
        $category_district_data = model('CategoryDistrict')->getCache();
        $cluelist = [];
        if (empty($list)) {
            $this->ajaxReturn(200, '获取数据成功', []);
        }
        $adminlist = $this->adminlist();
        foreach ($list['rows'] as $v) {
            $v['admin_username'] = isset($adminlist[$v['admin_id']]) ? $adminlist[$v['admin_id']] : '';
            $v['creator_username'] = isset($adminlist[$v['creat_id']]) ? $adminlist[$v['creat_id']] : '';
            $v['trade'] = isset($category_data[$v['trade']]) ? $category_data[$v['trade']] : '';
            $v['district1'] = isset($category_district_data[$v['district1']]) ? $category_district_data[$v['district1']] : '';
            $v['district2'] = isset($category_district_data[$v['district2']]) ? $category_district_data[$v['district2']] : '';
            $v['district3'] = isset($category_district_data[$v['district3']]) ? $category_district_data[$v['district3']] : '';
            if ($v['last_visit_time'] > 0) {
                $v['not_following_day'] = intval((time() - $v['last_visit_time']) / 86400);
            } else {
                $v['not_following_day'] = '';
            }
            unset($v['admin_id'], $v['last_visit_time']);
            $cluelist[] = $v;
        }
        $return['items'] = $cluelist;
        $this->ajaxReturn(200, '获取数据成功', $return);
    }

    /*
     * 线索删除
     * */
    public function delete()
    {
        $clue_id = input('get.clue_id/a', []);
        $clue_count = model('b2bcrm.CrmClue')->getDataNum(['a.id' => ['in', $clue_id]]);
        if ($clue_count <= 0) {
            $this->ajaxReturn(500, '线索id错误');
        }
        try {
            Db::startTrans();
            $clue_list = model('b2bcrm.CrmClue')->where('id', 'in', $clue_id)->column('id,name');
            $clue_del = model('b2bcrm.CrmClue')->clueDel($clue_id);
            if ($clue_del === false) {
                throw new \Exception(model('b2bcrm.CrmClue')->getError());
            }

            // 日志
            $log_field = '删除线索';
            foreach ($clue_list as $c_id => $c_name) {
                $log_field .= '{' . $c_name . '}(线索ID:' . $c_id . ')；';
            }
            $log_result = model('AdminLog')->writeLog(
                $log_field,
                $this->admininfo,
                0,
                4
            );
            if (false === $log_result) {
                throw new \Exception(model('AdminLog')->getError());
            }

            Db::commit();
            $this->ajaxReturn(200, '删除成功');
        } catch (\Exception $e) {
            Db::rollback();
            $this->ajaxReturn(500, $e->getMessage());
        }
    }

    public function adminlist()
    {
        return model('Admin')->where('status', 1)->column('id,username', 'id');
    }

    public function adminlists()
    {
        $data = $this->adminlist();
        $arr = [];
        foreach ($data as $k => $v) {
            $arr[] = [
                'id' => $k,
                'name' => $v
            ];
        }
        $this->ajaxReturn(200, '获取数据成功', $arr);
    }

    /**
     * 查看线索名称是否重复
     * zch
     * 2022.9.19
     */
    public function isNameRepeat()
    {
        $name = input('post.name/s', '', 'trim');
        $id = input('post.id/d', 0, 'intval');
        $return['sys_configs'] = model('b2bcrm.CrmSysConfig')
            ->where([
                'key' => 'thread_duplicate_name',
                'category' => 'thread'
            ])
            ->value('value');
        $return['clue_count'] = model('b2bcrm.CrmClue')
            ->where('name', $name)
            ->where('id', '<>', $id)
            ->count();
        $this->ajaxReturn(200, '获取数据成功', $return);
    }

    /**
     * 处理线索联系人
     * @access private
     * @param array $input
     * @param array $clueInfo [线索信息]
     * @return \Exception
     * Date：2022-11-22
     * @author edc
     */
    private function _handleClueContact($input, $clueInfo)
    {
        /**
         * 1、判断当前手机号是否在联系人表中，不存在就新增一条，并改为主要手机号
         * 2、存在的话只需要处理改为主要手机号标识即可
         * 3、主要标识只会存在一条
         */
        // 先将该线索的联系人主要标识置空
        $updateWhere = [
            'clue_id' => $clueInfo['id']
        ];
        $clueContactModel = db('crm_clue_contact');
        $updateResult = $clueContactModel->where($updateWhere)->update(['is_main' => 0]);
        if (false === $updateResult) {
            throw new \Exception('保存联系人失败');
        }

        $contactField = [
            'id',
            'contact',
            'mobile',
            'is_main',
        ];
        $contactWhere = [
            'clue_id' => $clueInfo['id'],
            'mobile' => $clueInfo['mobile']
        ];
        $contactInfo = $clueContactModel->field($contactField)->where($contactWhere)->find();
        if (is_null($contactInfo) || empty($contactInfo)) {
            // 新增（兼容联系人表中没有数据的情况）
            $contactInfo = [
                'clue_id' => $clueInfo['id'],
                'contact' => $input['contacts'],
                'mobile' => $input['mobile'],
                'is_main' => 1,
                'addtime' => time()
            ];
            $insertResult = $clueContactModel->insertGetId($contactInfo);
            if (empty($insertResult)) {
                throw new \Exception('新增联系人失败');
            }
        } else {
            $updateWhere = [
                'id' => $contactInfo['id']
            ];
            $updateData = [
                'contact' => $input['contacts'],
                'mobile' => $input['mobile'],
                'is_main' => 1,
                'updatetime' => time(),
            ];
            $updateResult = $clueContactModel->where($updateWhere)->update($updateData);
            if (false === $updateResult) {
                throw new \Exception('保存联系人失败');
            }
        }
    }

    /**
     * 校验重复的线索名称
     * @access public
     * @return array
     * Date：2022-11-23
     * @author edc
     */
    public function verifyRepeatClueName()
    {
        $clueName = input('get.clue_name/s', '', 'trim');
        $isResult = input('get.is_result/d', 0);

        // 生成线索查询条件
        $clueField = [
            'id',
            'name',
            'admin_id',
            '1 as type',
        ];
        $clueWhere = [
            'name' => $clueName
        ];
        $clueQuery = db('crm_clue')->field($clueField)->where($clueWhere);
        // 生成客户查询条件
        $companyField = [
            'id',
            'companyname as name',
            'admin_id',
            '2 as type',
        ];
        $companyWhere = [
            'companyname' => $clueName
        ];
        $companyQuery = db('company')->field($companyField)->where($companyWhere);

        if ($isResult == 0) {
            // 查询线索中是否有重复
            $clueInfo = $clueQuery->find();
            if (!is_null($clueInfo) && !empty($clueInfo)) {
                $this->ajaxReturn(200, '该线索已存在', ['is_repeat' => 1]);
            }
            // 查询客户中是否有重复
            $companyInfo = $companyQuery->find();
            if (!is_null($companyInfo) && !empty($companyInfo)) {
                $this->ajaxReturn(200, '该线索已存在', ['is_repeat' => 1]);
            }
        } else {
            /************** 获取重复结果 ****************/
            $clueList = $clueQuery->select();
            $companyList = $companyQuery->select();
            $list = array_merge($clueList, $companyList);
            if (!empty($list)) {
                // 获取全部销售
                $adminList = db('admin')->column('id,username');
                foreach ($list as &$info) {
                    $info['username'] = '';
                    if (isset($adminList[$info['admin_id']]) && !empty($adminList[$info['admin_id']])) {
                        $info['username'] = $adminList[$info['admin_id']];
                    }
                }
                $this->ajaxReturn(200, '获取成功', $list);
            }
        }

        $this->ajaxReturn(200, '未找到重复线索');
    }

    /**
     * 校验重复的手机号
     * @access public
     * @return array
     * Date：2022-11-23
     * @author edc
     */
    public function verifyRepeatMobile()
    {
        $mobile = input('get.mobile/s', '', 'trim');
        if (!fieldRegex($mobile, 'mobile')) {
            $this->ajaxReturn(500, '联系电话格式错误');
        }

        /************** 查询线索 ****************/
        $clueField = [
            'id',
            'name',
            'admin_id',
            '1 as type',
        ];
        $clueWhere = [
            'mobile' => $mobile
        ];
        $list = db('crm_clue')->field($clueField)->where($clueWhere)->select();
        /************** 查企业会员手机号 或 企业联系人手机号 ****************/
        $field = [
            'b.id',
            'b.companyname as name',
            'b.admin_id',
            '2 as type',
        ];
        $where = [
            'a.utype' => 1,
            'a.mobile|c.mobile' => $mobile
        ];
        $companyList = db('member')
            ->alias('a')
            ->join('company b', 'a.uid = b.uid')
            ->join('company_contact c', 'b.id = c.comid')
            ->field($field)
            ->where($where)
            ->select();
        if (!empty($companyList)) {
            $list = array_merge($list, $companyList);
        }

        if (!empty($list)) {
            // 获取全部销售
            $adminList = db('admin')->column('id,username');
            foreach ($list as &$info) {
                $info['username'] = '';
                if (isset($adminList[$info['admin_id']]) && !empty($adminList[$info['admin_id']])) {
                    $info['username'] = $adminList[$info['admin_id']];
                }
            }
        }
        $this->ajaxReturn(200, '获取成功', $list);
    }

    /**
     * 获取联系人列表
     * @access public
     * @return array
     * Date：2022-11-23
     * @author edc
     */
    public function getContactList()
    {
        $clueId = input('get.clue_id/d', 0, 'intval');
        if (empty($clueId)) {
            $this->ajaxReturn(500, '线索id错误');
        }
        // 线索表中的联系人为主要联系人
        $clueField = [
            '0 as contact_id',
            'contacts as contact',
            'mobile',
            'telephone',
            '"" as qq',
            '"" as email',
            '0 as sex',
            '1 as is_main'
        ];
        $clueWhere = [
            'id' => $clueId
        ];
        $clueInfo = db('crm_clue')->field($clueField)->where($clueWhere)->find();
        if (is_null($clueInfo) || empty($clueInfo)) {
            // 正常不会发生
            $this->ajaxReturn(500, '未获取到线索联系方式');
        }
        if (empty($clueInfo['contact']) && empty($clueInfo['mobile'])) {
            $clueInfo = [];
        }

        // 查询非主要的联系方式
        $contactField = [
            'id as contact_id',
            'contact',
            'mobile',
            'telephone',
            'qq',
            'email',
            'sex',
            'is_main'
        ];
        $contactWhere = [
            'clue_id' => $clueId,
            'is_main' => 0
        ];
        $contactList = db('crm_clue_contact')->field($contactField)->where($contactWhere)->select();
        $list = array_merge(!empty($clueInfo) ? [$clueInfo] : [], $contactList);
        $this->ajaxReturn(200, '获取成功', $list);
    }

    /**
     * 设置为主要联系人
     * @access public
     * @return array
     * Date：2022-11-23
     * @author edc
     */
    public function setAsMainContact()
    {
        $clueId = input('post.clue_id/d', 0, 'intval');
        if (empty($clueId)) {
            $this->ajaxReturn(500, '线索ID错误');
        }
        $clueField = [
            'id',
            'name',
            'mobile',
            'contacts',
            'telephone'
        ];
        $clueWhere = [
            'id' => $clueId
        ];
        $clueModel = db('crm_clue');
        $clueInfo = $clueModel->field($clueField)->where($clueWhere)->find();
        if (is_null($clueInfo) || empty($clueInfo)) {
            $this->ajaxReturn(500, '未找到该线索信息');
        }
        $contactId = input('post.contact_id/d', 0, 'intval');
        if (empty($contactId)) {
            $this->ajaxReturn(500, '联系人ID错误');
        }
        // 查询联系方式
        $contactField = [
            'id',
            'contact',
            'mobile',
            'is_main',
            'telephone'
        ];
        $contactWhere = [
            'id' => $contactId,
            'clue_id' => $clueId
        ];
        $clueContactModel = db('crm_clue_contact');
        $contactInfo = $clueContactModel->field($contactField)->where($contactWhere)->find();
        if (is_null($contactInfo) || empty($contactInfo)) {
            $this->ajaxReturn(500, '未获取到该联系方式');
        }
        if (empty($contactInfo['contact'])) {
            $this->ajaxReturn(500, '请先完善联系人姓名再来设置');
        }
        if (!$contactInfo['mobile'] && !$contactInfo['telephone']) {
            $this->ajaxReturn(500, '手机号和座机都未填写，不能设置为主要联系方式');
        }
        // 手机号格式正确才可以设为主要
        if (!empty($contactInfo['mobile']) && !fieldRegex($contactInfo['mobile'], 'mobile')) {
            $this->ajaxReturn(500, '手机号格式不正确，不能设置为主要联系方式');
        }
        if ($contactInfo['is_main'] == 1) {
            $this->ajaxReturn(500, '已经设置为主要联系方式啦~');
        }

        $clueModel = db('crm_clue');
        // 开启事务
        $clueModel->startTrans();
        try {
            /**
             * 兼容历史数据
             * 线索表中手机号如果没有存在联系人表就要添加一条进去
             */
            $contactWhere = [
                'clue_id' => $clueId,
                'mobile' => $clueInfo['mobile']
            ];
            $contactIds = $clueContactModel->where($contactWhere)->value('id');
            if (is_null($contactIds) || empty($contactIds)) {
                $contactData = [
                    'clue_id' => $clueId,
                    'contact' => $clueInfo['contacts'],
                    'mobile' => $clueInfo['mobile'],
                    'telephone' => $clueInfo['telephone'],
                    'addtime' => time()
                ];
                $result = $clueContactModel->insertGetId($contactData);
                if (empty($result)) {
                    throw new \Exception('添加联系人失败-请求SQL为：' . $clueContactModel->getLastSql());
                }
            }

            // 将设为主要的取消
            $updateWhere = [
                'clue_id' => $clueId,
                'is_main' => 1
            ];
            $updateData = [
                'is_main' => 0
            ];
            $result = $clueContactModel->where($updateWhere)->update($updateData);
            if (false === $result) {
                throw new \Exception('取消主要设置失败-请求SQL为：' . $clueContactModel->getLastSql());
            }
            // 设为主要
            $updateWhere = [
                'id' => $contactId,
                'clue_id' => $clueId,
            ];
            $updateData = [
                'is_main' => 1
            ];
            $result = $clueContactModel->where($updateWhere)->update($updateData);
            if (false === $result) {
                throw new \Exception('设为主要失败-请求SQL为：' . $clueContactModel->getLastSql());
            }
            // 更改线索联系人
            $updateWhere = [
                'id' => $clueId
            ];
            $updateData = [
                'mobile' => $contactInfo['mobile'],
                'contacts' => $contactInfo['contact'],
                'telephone' => $contactInfo['telephone']
            ];
            $result = $clueModel->where($updateWhere)->update($updateData);
            if (false === $result) {
                throw new \Exception('更改线索联系人失败-请求SQL为：' . $clueContactModel->getLastSql());
            }

            model('AdminLog')->writeLog(
                '设置{' . $contactInfo['contact'] . '}为线索{' . $clueInfo['name'] . '}(线索ID:' . $clueInfo['id'] . ')的主要联系人',
                $this->admininfo,
                0,
                3
            );

            // 提交事务
            $clueModel->commit();
        } catch (\Exception $e) {
            // 回滚事务
            $clueModel->rollback();
            saveLog('报错信息：' . json_encode(['Line' => $e->getLine(), 'File' => $e->getFile(), 'Message' => $e->getMessage()]));
            $this->ajaxReturn(500, '设置失败');
        }

        $this->ajaxReturn(200, '设置成功');
    }

    /**
     * 新增联系人
     * @access public
     * @return array
     * Date：2022-11-23
     * @author edc
     */
    public function addContact()
    {
        $clueId = input('post.clue_id/d', 0, 'intval');
        if (empty($clueId)) {
            $this->ajaxReturn(500, '线索ID错误');
        }
        $clueField = [
            'id',
            'name',
            'mobile',
            'contacts'
        ];
        $clueWhere = [
            'id' => $clueId
        ];
        $clueModel = db('crm_clue');
        $clueInfo = $clueModel->field($clueField)->where($clueWhere)->find();
        if (is_null($clueInfo) || empty($clueInfo)) {
            $this->ajaxReturn(500, '未找到该线索信息');
        }
        $inputData = [
            'contact' => input('post.contact/s', '', 'trim'),
            'mobile' => input('post.mobile/s', '', 'trim'),
            'telephone' => input('post.telephone/s', '', 'trim'),
            'qq' => input('post.qq/s', '', 'trim'),
            'email' => input('post.email/s', '', 'trim'),
            'sex' => input('post.sex/d', 0)
        ];
        if (empty($inputData['mobile']) && empty($inputData['telephone'])) {
            $this->ajaxReturn(500, '请填写手机号或公司座机二选一');
        }
        $validate = new Validate($this->rule, $this->message);
        $result = $validate->check($inputData);
        if (false === $result) {
            $this->ajaxReturn(500, $validate->getError());
        }
        if (!empty($inputData['mobile']) && !fieldRegex($inputData['mobile'], 'mobile')) {
            $this->ajaxReturn(500, '手机号格式不正确');
        }
        if (!empty($inputData['email']) && !fieldRegex($inputData['email'], 'email')) {
            $this->ajaxReturn(500, '邮箱格式不正确');
        }

        $clueContactModel = db('crm_clue_contact');
        // 开启事务
        $clueContactModel->startTrans();
        try {
            // 如果资源表中没有联系人就将新增的加进去，并设置为主要的
            if (empty($clueInfo['contacts']) && empty($clueInfo['mobile'])) {
                $updateWhere = [
                    'id' => $clueId
                ];
                $updateData = [
                    'contacts' => $inputData['contact'],
                    'mobile' => $inputData['mobile'],
                ];
                $result = $clueModel->where($updateWhere)->update($updateData);
                if (false === $result) {
                    throw new \Exception('修改线索联系人失败-请求SQL为：' . $clueModel->getLastSql());
                }
                $inputData['is_main'] = 1;
            }
            $inputData['clue_id'] = $clueId;
            $inputData['addtime'] = time();
            $contactId = $clueContactModel->insertGetId($inputData);
            if (empty($contactId)) {
                throw new \Exception('新增联系人失败-请求SQL为：' . $clueContactModel->getLastSql());
            }

            $link_phone = empty($inputData['mobile']) ? $inputData['telephone'] : $inputData['mobile'];
            model('AdminLog')->writeLog(
                '为线索{' . $clueInfo['name'] . '}(线索ID:' . $clueInfo['id'] . ')添加线索联系人，' . $inputData['contact'] . ' ' . $link_phone,
                $this->admininfo,
                0,
                2
            );

            // 提交事务
            $clueContactModel->commit();
        } catch (\Exception $e) {
            // 回滚事务
            $clueContactModel->rollback();
            saveLog('报错信息：' . json_encode(['Line' => $e->getLine(), 'File' => $e->getFile(), 'Message' => $e->getMessage()]));
            $this->ajaxReturn(500, '新增失败');
        }

        $this->ajaxReturn(200, '新增成功');
    }

    /**
     * 修改联系人
     * @access public
     * @return array
     * Date：2022-11-24
     * @author edc
     */
    public function editContact()
    {
        $clueId = input('post.clue_id/d', 0, 'intval');
        if (empty($clueId)) {
            $this->ajaxReturn(500, '线索ID错误');
        }
        $clueField = [
            'id',
            'name',
            'mobile',
            'contacts'
        ];
        $clueWhere = [
            'id' => $clueId
        ];
        $clueModel = db('crm_clue');
        $clueInfo = $clueModel->field($clueField)->where($clueWhere)->find();
        if (is_null($clueInfo) || empty($clueInfo)) {
            $this->ajaxReturn(500, '未找到该线索信息');
        }

        $contactInfo = [
            'contact' => '',
            'mobile' => '',
            'telephone' => '',
            'qq' => '',
            'email' => '',
            'sex' => 0,
            'is_main' => 0
        ];
        $contactId = input('post.contact_id/d', 0, 'intval');
        if (!empty($contactId)) {
            // 查询联系方式
            $contactField = [
                'id',
                'contact',
                'mobile',
                'telephone',
                'qq',
                'email',
                'sex',
                'is_main'
            ];
            $contactWhere = [
                'id' => $contactId,
                'clue_id' => $clueId
            ];
            $clueContactModel = db('crm_clue_contact');
            $contactInfo = $clueContactModel->field($contactField)->where($contactWhere)->find();
            if (is_null($contactInfo) || empty($contactInfo)) {
                $this->ajaxReturn(500, '未获取到该联系方式');
            }
        }

        $inputData = [
            'contact' => input('post.contact/s', '', 'trim'),
            'mobile' => input('post.mobile/s', '', 'trim'),
            'telephone' => input('post.telephone/s', '', 'trim'),
            'qq' => input('post.qq/s', '', 'trim'),
            'email' => input('post.email/s', '', 'trim'),
            'sex' => input('post.sex/d', 0)
        ];
        if (empty($inputData['mobile']) && empty($inputData['telephone'])) {
            $this->ajaxReturn(500, '请填写手机号或公司座机二选一');
        }
        $validate = new Validate($this->rule, $this->message);
        $result = $validate->check($inputData);
        if (false === $result) {
            $this->ajaxReturn(500, $validate->getError());
        }
        if (!empty($inputData['mobile']) && !fieldRegex($inputData['mobile'], 'mobile')) {
            $this->ajaxReturn(500, '手机号格式不正确');
        }
        if (!empty($inputData['email']) && !fieldRegex($inputData['email'], 'email')) {
            $this->ajaxReturn(500, '邮箱格式不正确');
        }

        $clueContactModel = db('crm_clue_contact');
        // 开启事务
        $clueContactModel->startTrans();
        try {
            if (!empty($contactId)) {
                $updateWhere = [
                    'id' => $contactId
                ];
                $inputData['updatetime'] = time();
                $result = $clueContactModel->where($updateWhere)->update($inputData);
                if (false === $result) {
                    throw new \Exception('修改联系人失败-请求SQL为：' . $clueContactModel->getLastSql());
                }
            }

            /*
             * 1.兼容老数据，没有联系人ID只修改线索联系人
             * 2.如果是主要，则同时修改线索联系人
             */
            if (
                empty($contactId)
                ||
                $contactInfo['is_main'] == 1
            ) {
                $updateWhere = [
                    'id' => $clueId
                ];
                $updateData = [
                    'mobile' => $inputData['mobile'],
                    'contacts' => $inputData['contact'],
                    'telephone' => $inputData['telephone']
                ];
                $result = $clueModel->where($updateWhere)->update($updateData);
                if (false === $result) {
                    throw new \Exception('修改线索联系人失败-请求SQL为：' . $clueModel->getLastSql());
                }
            }

            $log_field = '修改线索{' . $clueInfo['name'] . '}(线索ID:' . $clueInfo['id'] . ')联系人，';
            if ($contactInfo['contact'] != $inputData['contact']) {
                $log_field .= '姓名:' . (!empty($contactInfo['contact']) ? $contactInfo['contact'] : '无') . '->' . (!empty($inputData['contact']) ? $inputData['contact'] : '未填写') . '；';
            }
            if ($contactInfo['mobile'] != $inputData['mobile']) {
                $log_field .= '手机号:' . (!empty($contactInfo['mobile']) ? $contactInfo['mobile'] : '无') . '->' . (!empty($inputData['mobile']) ? $inputData['mobile'] : '未填写') . '；';
            }
            if ($contactInfo['telephone'] != $inputData['telephone']) {
                $log_field .= '公司座机:' . (!empty($contactInfo['telephone']) ? $contactInfo['telephone'] : '无') . '->' . (!empty($inputData['telephone']) ? $inputData['telephone'] : '未填写') . '；';
            }
            if ($contactInfo['qq'] != $inputData['qq']) {
                $log_field .= 'QQ:' . (!empty($contactInfo['qq']) ? $contactInfo['qq'] : '无') . '->' . (!empty($inputData['qq']) ? $inputData['qq'] : '未填写') . '；';
            }
            if ($contactInfo['email'] != $inputData['email']) {
                $log_field .= '邮箱:' . (!empty($contactInfo['email']) ? $contactInfo['email'] : '无') . '->' . (!empty($inputData['email']) ? $inputData['email'] : '未填写') . '；';
            }
            if ($contactInfo['sex'] != $inputData['sex']) {
                $log_field .= '性别:' . (!empty($contactInfo['sex']) ? model('Resume')->map_sex[$contactInfo['sex']] : '无') . '->' . (!empty($inputData['sex']) ? model('Resume')->map_sex[$inputData['sex']] : '未填写') . '；';
            }

            model('AdminLog')->writeLog(
                $log_field,
                $this->admininfo,
                0,
                3
            );

            // 提交事务
            $clueContactModel->commit();
        } catch (\Exception $e) {
            // 回滚事务
            $clueContactModel->rollback();
            saveLog('报错信息：' . json_encode(['Line' => $e->getLine(), 'File' => $e->getFile(), 'Message' => $e->getMessage()]));
            $this->ajaxReturn(500, '修改失败', ['err_msg' => $e->getMessage()]);
        }

        $this->ajaxReturn(200, '修改成功');
    }

    /**
     * 删除联系人
     * @access public
     * @return array
     * Date：2022-11-24
     * @author edc
     */
    public function deleteContact()
    {
        $contactId = input('post.contact_id/d', 0, 'intval');
        if (empty($contactId)) {
            $this->ajaxReturn(500, '联系人ID错误');
        }
        // 查询联系方式
        $contactField = [
            'id',
            'contact',
            'mobile',
            'is_main',
            'clue_id'
        ];
        $contactWhere = [
            'id' => $contactId
        ];
        $clueContactModel = db('crm_clue_contact');
        $contactInfo = $clueContactModel->field($contactField)->where($contactWhere)->find();
        if (is_null($contactInfo) || empty($contactInfo)) {
            $this->ajaxReturn(500, '未获取到该联系方式');
        }
        if ($contactInfo['is_main'] == 1) {
            $this->ajaxReturn(500, '主要联系方式不能被删除');
        }

        $clueField = [
            'id',
            'name',
        ];
        $clueWhere = [
            'id' => $contactInfo['clue_id']
        ];
        $clueModel = db('crm_clue');
        $clueInfo = $clueModel->field($clueField)->where($clueWhere)->find();
        if (is_null($clueInfo) || empty($clueInfo)) {
            $this->ajaxReturn(500, '未找到该线索信息');
        }

        $clueContactModel = db('crm_clue_contact');
        // 开启事务
        $clueContactModel->startTrans();
        try {
            $deleteWhere = [
                'id' => $contactId
            ];
            $result = $clueContactModel->where($deleteWhere)->delete();
            if (false === $result) {
                throw new \Exception('删除联系人失败-请求SQL为：' . $clueContactModel->getLastSql());
            }

            model('AdminLog')->writeLog(
                '删除线索{' . $clueInfo['name'] . '}(线索ID:' . $clueInfo['id'] . ')联系人',
                $this->admininfo,
                0,
                3
            );

            // 提交事务
            $clueContactModel->commit();
        } catch (\Exception $e) {
            // 回滚事务
            $clueContactModel->rollback();
            saveLog('报错信息：' . json_encode(['Line' => $e->getLine(), 'File' => $e->getFile(), 'Message' => $e->getMessage()]));
            $this->ajaxReturn(500, '删除失败');
        }

        $this->ajaxReturn(200, '删除成功');
    }

    /**
     * 校验重复的企业
     * @access public
     * @return array
     * Date：2022-11-24
     * @author edc
     */
    public function verifyRepeatCompany()
    {
        $clueId = input('get.clue_id/d', 0, 'intval');
        if (empty($clueId)) {
            $this->ajaxReturn(500, '线索ID错误');
        }
        $clueField = [
            'id',
            'name',
            'mobile'
        ];
        $clueWhere = [
            'id' => $clueId
        ];
        $clueModel = db('crm_clue');
        $clueInfo = $clueModel->field($clueField)->where($clueWhere)->find();
        if (is_null($clueInfo) || empty($clueInfo)) {
            $this->ajaxReturn(500, '未找到该线索信息');
        }

        /*
         * 1、用线索主要联系人手机号查企业会员手机号是否有重复
         * 2、用线索主要联系人手机号查企业联系人手机号是否有重复
         * 3、用线索名称查企业名称是否有重复
         * */
        /************** 查企业会员手机号 或 企业联系人手机号 ****************/
        $list = [];
        if (!empty($clueInfo['mobile'])) {
            $field = [
                'b.id',
                'b.companyname as name',
                'b.admin_id',
                'b.platform',
                'a.mobile as member_mobile',
                'c.mobile as company_mobile',
                'c.contact as company_contact',
                'b.addtime',
                '1 as type',
            ];
            $where = [
                'a.utype' => 1,
                'a.mobile|c.mobile' => $clueInfo['mobile']
            ];
            $list = db('member')
                ->alias('a')
                ->join('company b', 'a.uid = b.uid')
                ->join('company_contact c', 'b.id = c.comid')
                ->field($field)
                ->where($where)
                ->select();
        }

        /************** 查企业名称 ****************/
        if (!empty($clueInfo['name'])) {
            $field = [
                'b.id',
                'b.companyname as name',
                'b.admin_id',
                'b.platform',
                'a.mobile as member_mobile',
                'c.mobile as company_mobile',
                'c.contact as company_contact',
                'b.addtime',
                '2 as type',
            ];
            $where = [
                'a.utype' => 1,
                'b.companyname' => $clueInfo['name']
            ];
            $lists = db('member')
                ->alias('a')
                ->join('company b', 'a.uid = b.uid')
                ->join('company_contact c', 'b.id = c.comid')
                ->field($field)
                ->where($where)
                ->select();
            if (!empty($lists)) {
                $list = array_merge($list, $lists);
            }
        }

        if (!empty($list)) {
            // 获取全部销售
            $adminList = db('admin')->column('id,username');
            // 获取平台来源
            $platformList = model('BaseModel')->map_ad_platform;
            foreach ($list as &$info) {
                $info['unique_id'] = $info['type'] . '_' . $info['id'];
                $info['username'] = '';
                if (isset($adminList[$info['admin_id']]) && !empty($adminList[$info['admin_id']])) {
                    $info['username'] = $adminList[$info['admin_id']];
                }
                $info['platform'] = isset($platformList[$info['platform']]) && !empty($platformList[$info['platform']]) ?
                    $platformList[$info['platform']] :
                    '';
                $info['addtime'] = date('Y-m-d H:i:s', $info['addtime']);
            }
        }
        $this->ajaxReturn(200, '获取成功', $list);
    }

    /**
     * 合并线索到客户
     * @access public
     * @return array
     * Date：2022-11-25
     * @author edc
     */
    public function mergeClueToCompany()
    {
        $clueId = input('post.clue_id/d', 0, 'intval');
        if (empty($clueId)) {
            $this->ajaxReturn(500, '线索ID错误');
        }
        $clueField = [
            'id',
            'mobile',
            'contacts',
            'last_visit_admin',
            'last_visit_time',
        ];
        $clueWhere = [
            'id' => $clueId
        ];
        $clueInfo = db('crm_clue')->field($clueField)->where($clueWhere)->find();
        if (is_null($clueInfo) || empty($clueInfo)) {
            $this->ajaxReturn(500, '未找到该线索信息');
        }
        $companyId = input('post.company_id/d', 0, 'intval');
        if (empty($companyId)) {
            $this->ajaxReturn(500, '客户ID错误');
        }
        $companyField = [
            'id',
            'uid',
            'last_visit_admin',
            'last_visit_time',
        ];
        $companyWhere = [
            'id' => $companyId
        ];
        $companyModel = db('company');
        $companyInfo = $companyModel->field($companyField)->where($companyWhere)->find();
        if (is_null($companyInfo) || empty($companyInfo)) {
            $this->ajaxReturn(500, '未找到该客户信息');
        }

        // 单独组装线索的主要联系人，防止联系人表中没有该数据
        $currentTime = time();
        $contactList[] = [
            'comid' => $companyInfo['id'],
            'uid' => $companyInfo['uid'],
            'contact' => $clueInfo['contacts'],
            'mobile' => $clueInfo['mobile'],
            'weixin' => '',
            'telephone' => '',
            'qq' => '',
            'email' => '',
            'sex' => 0,
            'addtime' => $currentTime,
            'updatetime' => $currentTime,
        ];
        // 查询线索的所有联系人
        $contactField = [
            "$companyInfo[id] as comid",
            "$companyInfo[uid] as uid",
            'contact',
            'mobile',
            '"" as weixin',
            'telephone',
            'qq',
            'email',
            'sex',
            "$currentTime as addtime",
            "$currentTime as updatetime"
        ];
        $contactWhere = [
            'clue_id' => $clueId,
            'is_main' => 0
        ];
        $contactData = db('crm_clue_contact')->field($contactField)->where($contactWhere)->select();
        if (!empty($contactData)) {
            $contactList = array_merge($contactList, $contactData);
        }

        $companyContactModel = db('crm_company_contact');
        // 开启事务
        $companyContactModel->startTrans();
        try {
            // 合并联系人
            $result = $companyContactModel->insertAll($contactList);
            if (empty($result)) {
                throw new \Exception('添加客户联系人失败-请求SQL为：' . $companyContactModel->getLastSql());
            }
            // 判断企业最后跟进信息没有并且要合并的线索中有的话，就将线索中的最后跟进信息同步过去
            if (intval($clueInfo['last_visit_time']) > intval($companyInfo['last_visit_time'])) {
                $updateWhere = [
                    'id' => $companyId
                ];
                $updateData = [
                    'last_visit_time' => $clueInfo['last_visit_time'],
                    'last_visit_admin' => $clueInfo['last_visit_admin'],
                ];
                $result = $companyModel->where($updateWhere)->update($updateData);
                if (false === $result) {
                    throw new \Exception('更改客户最后跟进信息失败-请求SQL为：' . $companyModel->getLastSql());
                }
            }

            $crmClueRes = model('b2bcrm.CrmClue')->isUpdate('true')
                ->save(
                    [
                        'is_customer' => 1,
                        'utype' => 1,
                        'uid' => $companyInfo['uid']
                    ],
                    ['id' => $clueId]
                );
            if (false === $crmClueRes) {
                throw new \Exception('线索转换失败-错误：' . model('b2bcrm.CrmClue')->getError());
            }
            $crmFollowUpRes = model('b2bcrm.CrmFollowUp')
                ->isUpdate(true)
                ->save(
                    [
                        'uid' => $companyInfo['uid']
                    ],
                    [
                        'clue_id' => $clueId,
                        'type' => 1
                    ]
                );
            if (false === $crmFollowUpRes) {
                throw new \Exception('线索跟进记录转换失败-错误：' . model('b2bcrm.CrmFollowUp')->getError());
            }

            model('AdminLog')->writeLog(
                '合并线索到客户【线索ID:' . $clueId . '】，【客户ID:' . $companyId . '】',
                $this->admininfo
            );

            // 提交事务
            $companyContactModel->commit();
        } catch (\Exception $e) {
            // 回滚事务
            $companyContactModel->rollback();
            saveLog('报错信息：' . json_encode(['Line' => $e->getLine(), 'File' => $e->getFile(), 'Message' => $e->getMessage()]));
            $this->ajaxReturn(500, '合并失败');
        }

        $this->ajaxReturn(200, '合并成功');
    }

}
